"""FastAPI 应用入口

职责：
- 创建 FastAPI 实例
- 注册中间件与路由
- 启动时初始化数据库并引导默认管理员账号
"""

import os

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from sqlmodel import Session, select

from app.core.db import create_db_and_tables, engine
from app.core.auth import get_password_hash
from app.module.users.model import User, UserRole
from app.module.users.api import router as users_router
from app.module.users.api import auth_router as users_auth_router
from app.module.pages.api import router as pages_router
from app.module.reminder.api import router as reminder_router



def create_app() -> FastAPI:
    """创建并返回 FastAPI 应用实例"""

    app = FastAPI(title="User Management API", version="0.1.0")

    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    @app.on_event("startup")
    def on_startup() -> None:
        """应用启动钩子：建表，并确保至少存在一个管理员账号"""
        create_db_and_tables()
        with Session(engine) as session:
            admin = session.exec(select(User).where(User.role == UserRole.admin)).first()
            if admin is None:
                password = os.environ.get("ADMIN_PASSWORD", "admin123")
                admin_user = User(
                    username="admin",
                    hashed_password=get_password_hash(password),
                    disabled=False,
                    role=UserRole.admin,
                )
                session.add(admin_user)
                session.commit()

    # 注册路由模块
    # 用户模块（users_router + users_auth_router）
    app.include_router(users_auth_router)
    app.include_router(users_router)
    app.include_router(pages_router)
    app.include_router(reminder_router)
    return app


# app = create_app()


